#include "printview.h"

PrintView::PrintView()
{
setupUi(this);
readSettings();

QObject::connect( printToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( print_file() ) );
QObject::connect( pdfToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( print_pdf() ) );
}

void PrintView::writeSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);
settings.beginGroup( QLatin1String("PrintView") );
settings.setValue( QLatin1String("size"), QVariant( this->size() ) );
settings.setValue( QLatin1String("pos"), QVariant( this->pos() ) );
settings.endGroup();
}

void PrintView::readSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);                
settings.beginGroup( QLatin1String("PrintView") );
resize( settings.value( QLatin1String("size"), QSize( 628, 490 ) ).toSize() );
move( settings.value( QLatin1String("pos"), QPoint( 0, 0 ) ).toPoint() );
settings.endGroup();
}

void PrintView::closeEvent( QCloseEvent * e )
{
writeSettings();
e->accept();
}

void PrintView::set_doc(QTextDocument * doc)
{
textEdit->clear();
textEdit->setDocument( doc);
}

void PrintView::print_file()
{
QTextDocument * document = textEdit->document();
QPrinter printer;
QPrintDialog * dialog = new QPrintDialog( &printer, this );
    if ( dialog->exec() != QDialog::Accepted )
    {
    return;
    }
document->print( &printer );
}

void PrintView::print_pdf()
{
QString f = QFileDialog::getSaveFileName( this,
                                          tr("Create PDF File"),
                                          QString(),
                                          QLatin1String("*.pdf") );
    if ( true != f.isEmpty() )
    {
        if ( true == QFileInfo(f).suffix().isEmpty() )
        {
        f.append(".pdf");
        }
    QPrinter printer( QPrinter::HighResolution );
    printer.setOutputFileName(f);
    printer.setOutputFormat( QPrinter::PdfFormat );
        if ( NULL != textEdit->document() )
        {
        textEdit->document()->print(&printer);
        }
    }
}
